package com.itcast.googleplay;

import java.io.File;
import com.itcast.googleplay.domain.AppInfo;
import com.itcast.googleplay.holder.AppDesHolder;
import com.itcast.googleplay.holder.AppInfoHolder;
import com.itcast.googleplay.holder.AppPicHolder;
import com.itcast.googleplay.holder.AppSafeHolder;
import com.itcast.googleplay.protocol.DetailProtocol;
import com.itcast.googleplay.ui.LoadingPage;
import com.itcast.googleplay.ui.LoadingPage.ResultState;
import com.itcast.googleplay.utils.UIUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.sample.download.DownloadInfo;
import com.lidroid.xutils.sample.download.DownloadManager;
import com.lidroid.xutils.sample.download.DownloadService;
import com.lidroid.xutils.util.LogUtils;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

public class DetailActivity extends BaseActivity {
	private static final String TAG = "DetailActivity";
	private String packageName;
	private AppInfo data;
	private ScrollView scrollView;
	private ProgressBar download_bar;
	private TextView tv_download_state;
	private DownloadManager downloadManager = DownloadService.getDownloadManager(UIUtils.getContext());
	private DownloadStateListener downloadStateListener = new DownloadStateListener();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		packageName = getIntent().getStringExtra("packagename");
		Log.i(TAG, "====================packageName = "+packageName);
		initActionBar();
		
		LoadingPage loadingPage = new LoadingPage(UIUtils.getContext()) {
			
			@Override
			public ResultState onLoad() {
				return onDetailLoad();
			}
			
			@Override
			public View onCreateSuccessedView() {
				return onDetialSuccessedView();
			}
		};
		
		//使用loadingPage调用show方法,show方法开启子线程调用onLoad方法,onLoad方法调用了onDetailLoad方法请求网络就被触发
		if(loadingPage!=null){
			loadingPage.show();
		}
		//此方法等同于setContentView(R.layout.xxxx)
		//以下方法将LoadingPage设置给当前的activity,即维护了4中网络请求状态的帧布局设置给了当前activity
		setContentView(loadingPage);
	}

	private void registerProgressUpdate() {
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
		 if(downloadInfo!=null){
			 HttpHandler<File> handler = downloadInfo.getHandler();
			 if (handler != null) {
	             RequestCallBack callBack = handler.getRequestCallBack();
	             if (callBack instanceof DownloadManager.ManagerCallBack) {
	                 DownloadManager.ManagerCallBack managerCallBack = (DownloadManager.ManagerCallBack) callBack;
	                 if (managerCallBack.getBaseCallBack() != null) {
	                     managerCallBack.setBaseCallBack(downloadStateListener);
	                 }
	             }
	         }
		 }
	}

	private void initActionBar() {
		//1.获取actionBar对象
		ActionBar actionBar = getSupportActionBar();
		//2.修改actionBar图片和文字
		actionBar.setTitle("传智一期谷歌市场");
		actionBar.setIcon(R.drawable.ic_launcher);
		
		//3.设置左上角三条线的图片可见,此段api必须和setDisplayHomeAsUpEnabled一起使用,否则无效
		actionBar.setDisplayShowHomeEnabled(true);
		//4.设置actionBar左上角的按钮可以使用
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == android.R.id.home){
//			Toast.makeText(UIUtils.getContext(), "结束activity界面", 0).show();
			finish();
		}
		return super.onOptionsItemSelected(item);
	}

	protected View onDetialSuccessedView() {
		View view = UIUtils.inflate(R.layout.activity_detail);
		
		scrollView = (ScrollView) view.findViewById(R.id.scv);
		download_bar = (ProgressBar) view.findViewById(R.id.download_bar);
		tv_download_state = (TextView) view.findViewById(R.id.tv_download_state);
		
		download_bar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				download();
			}
		});
		
		//描述信息所在的帧布局逻辑
		FrameLayout flAppInfo = (FrameLayout) view.findViewById(R.id.fl_app_info);
		//1.创建holder对象,让其继承至BaseHolder
		AppInfoHolder appInfoHolder = new AppInfoHolder();
		//2.给holder传递数据,让initData方法可以使用数据填充控件
		appInfoHolder.setData(data);
		//3.添加AppInfoHolder在initView方法返回的页面效果
		flAppInfo.addView(appInfoHolder.getConvertView());
		
		
		//可扩展的安全信息帧布局的相关逻辑
		FrameLayout flAppSafe = (FrameLayout) view.findViewById(R.id.fl_app_safe);
		AppSafeHolder appSafeHolder = new AppSafeHolder();
		appSafeHolder.setData(data);
		flAppSafe.addView(appSafeHolder.getConvertView());
		
		FrameLayout flAppPic = (FrameLayout) view.findViewById(R.id.fl_app_pic);
		AppPicHolder appPicHolder = new AppPicHolder();
		appPicHolder.setData(data);
		flAppPic.addView(appPicHolder.getConvertView());
		
		FrameLayout flAppDes = (FrameLayout) view.findViewById(R.id.fl_app_des);
		AppDesHolder appDesHolder = new AppDesHolder();
		appDesHolder.setScrollView(scrollView);
		appDesHolder.setData(data);
		flAppDes.addView(appDesHolder.getConvertView());
		
		refreshUI();
		registerProgressUpdate();
		
		return view;
	}

	protected void download() {
    	DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
    	
    	if (downloadInfo == null) {
    		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    			String target = Environment.getExternalStorageDirectory()
	    			+File.separator
	    			+"googlePlay0817"
	    			+File.separator
	    			+"download"
	    			+File.separator
	    			+data.name+".apk";
    			String appUrl = "http://127.0.0.1:8090/download?name="+data.downloadUrl;
    			try {
					downloadManager.addNewDownload(data.id+"", appUrl,
					      data.name,		// 保存到数据库时候的一个应用名称
					      target,		// 指定保存路径和保存的文件名
					      true, 		// 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
					      false, 		// 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
					      downloadStateListener);// 用于接收下载状态的监听器
				} catch (DbException e) {
					e.printStackTrace();
				}		
    		}
		}else {
			// 如果原来下载过，则要么暂停，要继续
			HttpHandler.State state = downloadInfo.getState();
            switch (state) {
                case WAITING:
                case STARTED:
                case LOADING:
                	// 如果原来是等待、开始、正在下载，则暂停
                    try {
                        downloadManager.stopDownload(downloadInfo);	// 暂停下载
                    } catch (DbException e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                    break;
                case CANCELLED:
                case FAILURE:
                	// 如果原来暂停了下载，或者下载失败了，则重新下载，如果暂停的话是断点续传地下载
                    try {
                        downloadManager.resumeDownload(downloadInfo, downloadStateListener);	// 第二个参数用于接收下载状态
                    } catch (DbException e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                    break;
                case SUCCESS:
                	installApk();
                	break;
                default:
                    break;
            }
		}
    	refreshUI();
	}
	
	 /** 下载状态监听器  */
    private class DownloadStateListener extends RequestCallBack<File> {

    	/** 下载失败 */
		@Override
		public void onFailure(HttpException arg0, String arg1) {
			refreshUI();
		}

		/** 下载成功 */
		@Override
		public void onSuccess(ResponseInfo<File> arg0) {
			refreshUI();
		}

		/** 取消下载 */
		@Override
		public void onCancelled() {
			refreshUI();
		}

		/** 正在下载*/
		@Override
		public void onLoading(long total, long current, boolean isUploading) {
			refreshUI();
		}

		/** 开始下载 */
		@Override
		public void onStart() {
			refreshUI();
		}
		
    }

	protected ResultState onDetailLoad() {
		DetailProtocol detailProtocol = new DetailProtocol();
		data = detailProtocol.getData("detail", -1, "packageName="+packageName);
		if(data != null){
			return ResultState.STATE_SUCCESSED;
		}
		return ResultState.STATE_ERROR;
	}

	public void refreshUI() {
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
		if (downloadInfo == null) {
			// 如果原来没有下载过，则显示成下载
			tv_download_state.setText("下载");
    		return;
		}
		
		HttpHandler.State state = downloadInfo.getState();	// 获取当前下载信息的下载状态
        switch (state) {
            case WAITING:
            	tv_download_state.setText("等待");
            	break;
            case STARTED:
            	tv_download_state.setText("开始下载");
            	break;
            case CANCELLED:// 如果原来是等待、开始、正在下载或者暂停的状态，则需要显示下载进度
            	if(downloadInfo.getFileLength()>0){
            		int progressloading = (int) (downloadInfo.getProgress()*100/downloadInfo.getFileLength());
            		download_bar.setProgress(progressloading);
            	}
            	tv_download_state.setText("继续");
                break;
            case LOADING:
            	if(downloadInfo.getFileLength()>0){
            		int progressloading = (int) (downloadInfo.getProgress()*100/downloadInfo.getFileLength());
            		download_bar.setProgress(progressloading);
            		tv_download_state.setText(progressloading+"%");
            	}
            	break;
            case SUCCESS:
            	tv_download_state.setText("安装");
                break;
            case FAILURE:
            	tv_download_state.setText("重试");
                break;
            default:
                break;
        }
		
	}

	private void installApk() {
		Intent intent = new Intent("android.intent.action.VIEW");
		//匹配category
		intent.addCategory("android.intent.category.DEFAULT");
		//匹配data数据源
		//匹配数据类型
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
		intent.setDataAndType(Uri.parse("file://"+downloadInfo.getFileSavePath()),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}
}
